<!-- 滑动操作组件 -->
<template>
	<view class="swipe-action" :class="{ 'swipe-action--opened': isOpened }">
		<!-- 内容区域 -->
		<view class="swipe-action__content" @touchstart="touchStart" @touchmove="touchMove" @touchend="touchEnd">
			<slot></slot>
		</view>
		
		<!-- 操作按钮区域 -->
		<view class="swipe-action__buttons" :style="buttonsStyle">
			<view 
				v-for="(button, index) in buttons" 
				:key="index"
				class="swipe-action__button"
				:style="button.style"
				@tap="onButtonTap(index)"
			>
				{{ button.text }}
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, computed } from 'vue';

const props = defineProps({
	// 按钮配置
	buttons: {
		type: Array,
		default: () => []
	},
	// 是否自动关闭其他已打开项
	autoClose: {
		type: Boolean,
		default: true
	},
	// 按钮宽度
	buttonWidth: {
		type: Number,
		default: 80
	}
});

const emit = defineEmits(['action']);

// 状态
const isOpened = ref(false);
const startX = ref(0);
const moveX = ref(0);
const buttonsWidth = computed(() => props.buttons.length * props.buttonWidth);

// 按钮区域样式
const buttonsStyle = computed(() => ({
	width: `${buttonsWidth.value}px`,
	transform: `translateX(${moveX.value}px)`
}));

// 触摸开始
const touchStart = (e) => {
	startX.value = e.touches[0].clientX;
};

// 触摸移动
const touchMove = (e) => {
	const currentX = e.touches[0].clientX;
	const diffX = currentX - startX.value;
	
	// 限制滑动范围
	if (diffX < 0) {
		moveX.value = Math.max(-buttonsWidth.value, diffX);
	} else {
		moveX.value = Math.min(0, diffX);
	}
};

// 触摸结束
const touchEnd = () => {
	const threshold = buttonsWidth.value * 0.3; // 30% 的阈值
	
	if (Math.abs(moveX.value) > threshold) {
		// 超过阈值，打开或关闭
		moveX.value = isOpened.value ? 0 : -buttonsWidth.value;
		isOpened.value = !isOpened.value;
	} else {
		// 未超过阈值，恢复原状
		moveX.value = isOpened.value ? -buttonsWidth.value : 0;
	}
};

// 按钮点击
const onButtonTap = (index) => {
	emit('action', {
		button: props.buttons[index]
	});
	
	if (props.autoClose) {
		moveX.value = 0;
		isOpened.value = false;
	}
};
</script>

<style lang="scss">
.swipe-action {
	position: relative;
	width: 100%;
	overflow: hidden;
	
	&__content {
		position: relative;
		z-index: 1;
		background-color: #fff;
		transition: transform 0.3s ease;
	}
	
	&__buttons {
		position: absolute;
		top: 0;
		right: 0;
		height: 100%;
		display: flex;
		transition: transform 0.3s ease;
	}
	
	&__button {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 100%;
		padding: 0 20rpx;
		font-size: 28rpx;
		white-space: nowrap;
	}
}
</style> 